<template>
    <view class="px-2 py-4">
        <form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
            :startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
            :startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
            :resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />

    </view>
</template>

<script setup lang="ts">
import {
    onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick } from 'vue'
import { isEmpty } from '@/utils/is'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DefinitionApi from '@/api/bpm/definition'
import { GeneralContractApi, GeneralContractVO } from '@/api/legal/contractManager/generalcontract'
import { getAccessToken } from '@/utils/auth'
import { useApprovedTasksStore } from '@/store/modules/approvedTasksStore';
import { useUserStore } from '@/store/modules/user'
import { formatDate, formatPast2 } from '@/utils/formatTime'
import { getFileName, parseArrayField, buildFileList } from '@/utils/fileUtils'
import { useMessage, useToast } from 'wot-design-uni'


const globalConfig = (getApp() as any).globalData.config;
const message = useMessage()
const toast = useToast()
const detailId = ref(null)
const resubmit = ref(0)
const headerObj = ref(
    {
        Authorization: 'Bearer ' + getAccessToken()
    }
)
// 指定审批人
const processDefineKey = 'fw-ContractReviewSingle' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
    eids: []
})

const formFields = ref<any[]>([
    { type: 'input', prop: 'contractName', label: '合同名称', placeholder: '请输入合同名称' },
    { type: 'input', prop: 'contractNumber', label: '合同编号', placeholder: '请输入合同编号' },
    { type: 'input', prop: 'partyA', label: '甲方', placeholder: '请输入甲方' },
    { type: 'input', prop: 'partyB', label: '乙方', placeholder: '请输入乙方' },
    {
        type: 'radio',
        prop: 'isParty',
        label: '是否为第三方',
        width: 150,
        options: [
            { label: '是', value: 1 },
            { label: '否', value: 0 }
        ],
        optionLabel: 'label',
        optionValue: 'value',
        inline: true,
    },
    {
        type: 'input', prop: 'partyC', label: '丙方', placeholder: '请输入丙方',
        visible: (formData: any) => formData.isParty === true,
    },
    { type: 'input', prop: 'contractType', label: '合同类别', placeholder: '请输入合同类别' },
    { type: 'input', prop: 'contractAmount', label: '合同金额', placeholder: '请输入合同金额' },
    { type: 'input', prop: 'company', label: '所属企业', placeholder: '请输入所属企业' },
    { type: 'input', prop: 'handlerContact', label: '承办联系人', placeholder: '请输入承办联系人' },
    { type: 'input', prop: 'handlerPhone', label: '承办联系人电话', placeholder: '请输入电话' },
    {
        type: 'radio',
        prop: 'isAuthorized',
        label: '是否授权',
        width: 150,
        options: [
            { label: '是', value: 1 },
            { label: '否', value: 0 }
        ],
        optionLabel: 'label',
        optionValue: 'value',
        inline: true,
    },

    { type: 'input', prop: 'authorizedPerson', label: '委托代理人姓名', placeholder: '请输入委托代理人姓名' },
    { type: 'input', prop: 'remark', label: '备注', placeholder: '请输入备注' },
    {
        type: 'upload', prop: 'eids', label: '附件', placeholder: '请输入附件',
        action: globalConfig.uploadUrl,
        // limit: 1,
        accept: 'all',
        isMultipleArray: true,
        header: headerObj.value,
        targetMapping: {         // 字段映射配置
            fileUrl: 'eids',    // 接口返回ID -> formData.serverIds
            fileName: 'ename'     // 文件名 -> formData.fileName
        }
    },
])

const formData = ref<GeneralContractVO>({
    id: undefined,
    contractName: undefined,
    contractNumber: undefined,
    partyA: undefined,
    partyB: undefined,
    isParty: undefined,
    partyC: undefined,
    contractType: undefined,
    contractAmount: undefined,
    company: undefined,
    handlerContact: undefined,
    handlerPhone: undefined,
    isAuthorized: undefined,
    authorizedPerson: undefined,
    remark: undefined,
    isType: 0 // 1 一般合同

} as any)
const formRules = reactive({
    contractName: [
        {
            required: true,
            message: '请输入合同名称',
            trigger: ['blur', 'change'],
        },
    ],
    contractNumber: [
        {
            required: true,
            message: '请输入合同编号',
            trigger: ['blur', 'change'],
        },
    ],
    partyA: [
        {
            required: true,
            message: '请输入甲方',
            trigger: ['blur', 'change'],
        },
    ],
    partyB: [
        {
            required: true,
            message: '请输入乙方',
            trigger: ['blur', 'change'],
        },
    ],
    isParty: [
        {
            required: true,
            message: '是否为第三方',
            trigger: ['blur', 'change'],
        },
    ],
    contractType: [
        {
            required: true,
            message: '请输入合同类别',
            trigger: ['blur', 'change'],
        },
    ],
    contractAmount: [
        {
            required: true,
            message: '请输入合同金额',
            trigger: ['blur', 'change'],
        },
    ],
    company: [
        {
            required: true,
            message: '请输入所属企业',
            trigger: ['blur', 'change'],
        },
    ],
    handlerContact: [
        {
            required: true,
            message: '请输入承办联系人',
            trigger: ['blur', 'change'],
        },
    ],
    handlerPhone: [
        {
            required: true,
            message: '请输入电话',
            trigger: ['blur', 'change'],
        },
        {
            pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
            ,
            message: '请输入有效的电话号',
            trigger: ['blur', 'change'],
        },
    ],
    isAuthorized: [
        {
            required: true,
            message: '请输入是否授权',
            trigger: ['blur', 'change'],
        },
    ],
    authorizedPerson: [
        {
            required: true,
            message: '请输入委托代理人姓名',
            trigger: ['blur', 'change'],
        },
    ],
})


onLoad(async (options) => {
    const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
        undefined,
        processDefineKey
    )
    if (!processDefinitionDetail) {
        toast.error('流程模型未配置，请检查！')
        return
    }
    startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
    // 设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
        // 设置校验规则
        for (const userTask of startUserSelectTasks.value) {
            startUserSelectAssignees.value[userTask.id] = []
            startUserSelectAssigneesFormRules.value[userTask.id] = [
                {

                    required: true,
                    message: '请选择审批人',
                    validator: (value: any) => {
                        console.log("当前审批人值435435:", value); // 调试输出
                        if (value && Array.isArray(value) && value.length > 0) {
                            console.log('value.length', value.length);
                            return Promise.resolve();
                        } else {
                            return Promise.reject('审批人不能为空');
                        }
                    },
                    trigger: ['change']

                }
            ]
        }
        console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
        console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
    }
    detailId.value = options?.id
    resubmit.value = options?.resubmit
    /** 获得详情 */
    if (detailId.value) { getDetailById() }
})

/** 获取页面详情 */
const getDetailById = async () => {
    try {
        const data = await GeneralContractApi.getGeneralContract(Number(detailId.value))
        formData.value = data
        // 附件字段回显
        formData.value.eids = parseArrayField(data.eids);
        formData.value.ename = parseArrayField(data.ename);
        fileLists.value.eids = buildFileList(formData.value.eids, formData.value.ename) as any;
        console.log('formData.value', formData.value);
    } catch (error) {
        console.log('加载数据失败')
    }
}

/** 提交表单 */
const submitForm = async (payload: any) => {
    const { type, data } = payload
    try {
        if (type === 'update') {
            await GeneralContractApi.updateGeneralContract(data)
            toast.success('编辑成功');
        } else {
            await GeneralContractApi.createGeneralContract(data)
            toast.success('新增成功');
        }
        // 成功后跳转
        uni.navigateTo({ url: '/pagesPackage/Legal/contractManager/index' });
    } catch (error) {
        console.error('表单提交失败:', error);
        toast.error('提交失败，请稍后再试');
    }
}

/** 取消表单 */
const cancelForm = async () => {
    try {
        // 删除的二次确认
        await message.confirm({
            msg: '您确定要取消吗？',
            title: '提示'  // 添加标题
        })
        uni.navigateTo({ url: '/pagesPackage/Legal/contractManager/index' });
        // 显示成功提示
        toast.success('取消成功')
    } catch (error) {
        console.log('用户取消了操作或发生错误:', error)
    }
}
</script>

<style scoped lang="scss">
.container {
    padding: 20px 5px;
}

.custom-shadow {
    width: 40%;
    border-radius: 5%;
}
</style>